var  BASE = BASE||{}; //全局公用方法
$(function () {
    BASE.COMMON.userInfoFill(); /*头部用户信息*/
    BASE.COMMON.getQQList();
    BASE.COMMON.getUserData();
});
BASE.COMMON = (function () {
    var SCROLLFLAG =  true;
    /***********************公用方法start***********************/
  
    /*获取用户信息*/
    function getUserData() {
        if(BASE.getStore('userInfo')&&location.pathname!='/'&&location.pathname!='/index.html'){
            return;
        }
        BASE.getCommon('/device/member/detail',function (res) {
            if(res.code!==200){
                BASE.clearAll();
                BASE.COMMON.userInfoFill(); /*头部用户信息*/
                return;
            }
            var userInfo = res.data.member;
            BASE.setStore('userInfo',userInfo);
            BASE.COMMON.userInfoFill(); /*头部用户信息*/
            if($('#loginInfo').length>0){
                $('#loginInfo').html(template('loginInfo_tpl',userInfo));
            }
        });
    }
    /*获取用户id*/
    function getUserId() {
        var userInfo = BASE.getStore('userInfo');
        if(!userInfo){
            return '';
        }
        return userInfo.id;
    }
    /*获取浏览器请求id*/
    function getId() {
        var href =location.pathname;
        return href.split('/')[1];
    }
    /*五星评价获取评分的结果*/
    function getcommentResult(){
        var data = {};
        $('#commentScore .star-item-box').each(function (index, value) {
            data['star'+(index/1+1)] = $(value).find('.hover').length*0.4; /*一星0.4分*/
        });
        return data;
    }
    /*头部用户信息显示*/
    function userInfoFill() {
        var userInfo = BASE.getStore('userInfo');
        var $dom =  $('#header .header-user');
        if(!userInfo){
            $dom.find('.loginOut').show();
            $dom.find('.loginIn').hide();
            return;
        }
        $dom.find('.loginIn').show();
        $dom.find('.loginOut').hide();
        var userHead = userInfo.header;
        var headsrc = userHead;
        if (userHead && userHead.indexOf('http') <0){
            headsrc = BASE.baseImgURL+'/'+userHead;
        }
        if(headsrc){
            $('#header .headerUserImg').attr('src',headsrc);
        }
       
        $('#header .headerUserName').text(userInfo.nickName||'未知');
    }
    /*回复前数据存放*/
    function replyPrev(obj) {
        $('body').data('commentid',$(obj).data('commentid')); //需要回复的 评论ID
        $('body').data('replyid',$(obj).data('replyid')); //回复谁(ID)
        $(obj).parents('li.comment-item').find('.reply-textarea-box').slideToggle()
    }
    /***********************公用方法end**********************/
    
    /***********************公用接口start***********************/
    /*获取达人推荐列表*/
    function recommendDarenList(pageNum,pageSize) {
        var userId = BASE.COMMON.getUserId();
        var sendData = {

            pageNum:pageNum,
            pageSize:pageSize,
        };
        if(userId){
            sendData.needStatus=true;
        }
        BASE.apiGet('/device/member/recommendDaren',sendData,function (res) {
            var list = res.list;
            var data = {
                list:list,
                userId:userId,
            };
            $('#recommendDarenList').html(template('recommendDarenList_tpl',{data:data}));
        })
    }
    /*获取评论和回复的内容*/
    function getCommentReply(page){
        var id = getId();
        var sendData = {
            pageNum:page,
            pageSize:15,
            relatedId:id,
            type:$('#box').data('comment_type'),//类型(1视频 2 bbs，作业 3悬赏4项目5图文6电话7远程8互助9招聘)
        };
        if(BASE.COMMON.getUserId()){
            sendData.needStatus =  true;
        }
        BASE.apiGet('/device/comment/list',sendData,function (res) {
            $('#commentList').html(template('commentList_tpl',{data:{
                commentList:res.list,
                userId:getUserId(),
                sendId:$('#content').data('memberid'),
                recvMemberId:$('#box').data('recv_memberid'),
            }}));
            paging(res.pageNum,res.pages,getCommentReply);
        })
    }
    /*添加评论*/
    function addComment(obj) {
        var id = BASE.COMMON.getId();
        var sendData = {
            content :$('#comment_content').val(),
            relatedId: id,
            type : $('#box').data('comment_type'), //类型(1视频 2 bbs，作业，作业 3悬赏4项目5图文6电话7远程8互助9招聘)
        };
        if(!sendData.content){
            BASE.clearpop('请填写评论的内容');
            return;
        }
        $('obj').attr('disabled',true);
        BASE.postHttp('/device/comment/add',sendData,function (res) {
            $('obj').attr('disabled',false);
            if(res.code!=200){
                BASE.clearpop(res.message);
                return;
            }
            BASE.clearpop('成功');
            $('#comment_content').val('');
            if(location.href.indexOf('source_content')>-1||location.href.indexOf('blog_content')>-1){
                window.location.reload();
                return;
            }
            getCommentReply(1);
        })
    }
    /*添加回复*/
    function addReply(obj,callback) {
        var $textares = $(obj).parents('li.comment-item').find('textarea');
        var sendData = {
            content:$textares.val(),
            commentId:$('body').data('commentid'),
            replyToMemberId:$('body').data('replyid'),
        };
        if (!sendData.content){
            BASE.clearpop('请填写回复内容');
            $textares.focus();
            return;
        }
        BASE.apiPost('/device/comment/reply',sendData,function () {
            BASE.clearpop('回复成功');
            if(callback && typeof callback =='function'){
                callback(obj);
                return;
            }
            getCommentReply(1);
        })
    }
    /*获取状态*/
    function getStatus(relatedId,type,callback) {
        if(!BASE.COMMON.getUserId()){
            return;
        }
        var sendData = {
            relatedId:relatedId,
            type:type, //1,视频,2代码,3bbs,4线上班,9博客附件，10博客内容
        };
        BASE.apiGet('/device/mstatus/detail',sendData,function (res) {
            if(!res){
                if(callback&&typeof callback =="function"){
                    callback(res);
                }
                return;
            }
            for(var key in res){
                if(res[key]){
                    $('#'+key+' span:eq(0)').hide();
                    $('#'+key+' span:eq(1)').show();
                }else{
                    $('#'+key+' span:eq(1)').hide();
                    $('#'+key+' span:eq(0)').show();
                }
            }
            if(callback&&typeof callback =="function"){
                callback(res);
            }
        })
    }
    /*是否关注某个人*/
    function isNotice(id,dom) {
        var sendData = {
            toMemberId:id,
        };
        if(!BASE.COMMON.getUserId()){
            dom.find('button:eq(0)').show();
            return;
        }
        if(!id || id ==undefined){
            return;
        }
        BASE.apiGet('/device/mfollow/getFollowIs',sendData,function (res) {
            if(res){
                dom.find('button:eq(1)').show();
                return;
            }
            dom.find('button:eq(0)').show();
        })
    }
    /*关注*/
    function noticeToMember(obj) {
        var sendData = {
            toMemberId:$(obj).data('memberid'),
        };
        BASE.apiPost('/device/mfollow/add',sendData,function (res) {
            $(obj).hide().next().fadeIn();
        })
    }
    /*已关注*/
    function cancelNotice(obj) {
        var sendData = {
            toMemberId:$(obj).data('memberid'),
        };
        BASE.apiPost('/device/mfollow/unfollow',sendData,function (res) {
            $(obj).hide().prev().fadeIn();
        })
    }
   
    /*vip购买*/
    function buyVip(id,obj) {
        $(obj).attr('disabled',true);
        BASE.postHttp('/device/order/vip/buy',{sysProductId:id},function (res) {
            if(res.code!=200){
                BASE.clearpop(res.message);
                $(obj).attr('disabled',false);
                return;
            }
            var userInfo = BASE.getStore('userInfo');
            if (userInfo){
                userInfo.memberType='V';
                BASE.setStore('userInfo',userInfo);
            }
            location.href = '/userSubmitOrder.html?id='+res.data.id;
        })
    }
    /*获取省市区 2，省，3市 4 区域 不传 所有*/
    function getArea(level,id,pid,callback) {
        var sendData = {
            level:level,
        };
        if(pid){
            sendData.pid = pid;
        }
        BASE.apiGet('/device/area/list',sendData,function (res) {
            if(id == 'cityId'){
                $('#areaId').html(template('areaId_tpl',{data:{}}));
            }
            $('#'+id).html(template(id+'_tpl',{data:res.list}));
            if(callback &&typeof callback=='function'){
                callback();
            }
        })
    }
    /*获取商品价格*/
    function getGoodsPrice(type,callback){
        var sendData = {
            type:type,	//类型((类型: 1快速图文 2快速电话 3快速远程 4vip 5iosVip 6心意 7达人图文 8达人电话 9达人远程 10达人收徒,)
        };
        BASE.apiGet('/device/sysProduct/list',sendData,function (res) {
            if(callback&&typeof callback == 'function'){
                callback(res);
            }
        })
    }
    /*收藏视频*/
    function collectVideo(obj) {
        var id =$(obj).data('id');
        BASE.apiPost('/device/videoInfo/collect',{videoInfoId:id},function () {
            $(obj).hide().next().fadeIn();
        })
    }
    /*取消收藏视频*/
    function cancelcollectVideo(obj) {
        var id =$(obj).data('id');
        BASE.apiPost('/device/videoInfo/uncollect',{videoInfoId:id},function () {
            $(obj).hide().prev().fadeIn();
        })
    }
    /*获取评论的内容*/
    function getCommentScore(page){
        var $this = $(this);
        var flag = $this.data('flag');
        var id = BASE.COMMON.getId();
        var sendData = {
            pageNum:page,
            pageSize:15,
            relatedId:id,
            type:$('#box').data('comment_type'),
        };
        if(BASE.COMMON.getUserId()){
            sendData.needStatus =  true;
        }
        if(flag){
            return;
        }
        BASE.apiGet('/device/scoreComment/list',sendData,function (res) {
            $('#commentList').html(template('commentList_tpl',{data:{
                commentList:res.list,
                userId:BASE.COMMON.getUserId(),
            }}));
            $this.data('flag',true);
            paging(res.pageNum,res.pages,getCommentScore)
        })
    }
    /*添加评分评论*/
    function addCommentScore(obj) {
        var sendData = BASE.COMMON.getcommentResult();
        sendData.relatedId =BASE.COMMON.getId();
        sendData.content = $('#comment_content').val();
        sendData.noNameIs = $('#noNameIs').is(':checked')?true:false;
        sendData.type = $('#box').data('comment_type'); //1视频专辑,2书籍,3线上班,4软件
        $('obj').attr('disabled',true);
        BASE.postHttp('/device/scoreComment/add',sendData,function (res) {
            if(res.ecode == 'DATA_DUPLICATE_EXCEPTION'){
                BASE.clearpop('不能重复评论');
                return;
            }
            if(res.code != 200 && res.ecode != 'DATA_DUPLICATE_EXCEPTION' ){
                BASE.clearpop(res.message);
                return;
            }
            $('obj').attr('disabled',false);
            BASE.clearpop('评论成功');
            $('#comment_content').val('');
            getCommentScore(1);
        })
    }
    /*增加bbs的浏览次数*/
    function addbbsClick() {
        BASE.apiPost('/device/bbs/click',{id:BASE.COMMON.getId()});
    }
    /*获取qq列表*/
    function getQQList() {
        var qqlist =  BASE.getStore('qqlist');
        if(qqlist){
            qqlist = JSON.parse(qqlist);
            $('#qqLists').html(template('qqLists_tpl',{list:qqlist}));
            return;
        }
        BASE.apiGet('/device/member/kefuList',function (res) {
            BASE.setStore('qqlist',res);
            $('#qqLists').html(template('qqLists_tpl',{list:res}));
        })
    }
    /***********************公用接口end***********************/

    /***********************公用事件绑定start***********************/
    /*根据页面来源添加左侧导航的样式*/
    function urlLeftNav() {
        var link = window.location.pathname;
        if(link === '/'){
            link='/index.html';
        }
        link = link.substr(1).split('.html')[0];
        if(link.indexOf('_') > -1){
            link = link.split('_')[0];
        }
        $('#url_'+link).addClass('hover').siblings().removeClass('hover');
    }
   /*页面内容导航公用后样式显示*/
    function ulrContentNav() {
        var link = window.location.pathname;
        if(link.indexOf('/answer_') < 0){
            return;
        }
        link = link.substr(1).split('.html')[0];
        $('#contentNav .url_'+link).addClass('hover').siblings().removeClass('hover');

    }
    /*   /!*分类的更多是否显示*!/
    function initShowMore() {
        var category = $('#middle .category');
        category.each(function () {
            var navH = $(this).height();
            var navulH = $(this).find('ul').height();
            if(navulH > navH){
                $(this).find('.more').show();
            }else {
                $(this).find('.more').hide();
            }
        })
    }*/
    /*评分*/
    function commentStar(event) {
        $('#commentScore .star-item-box').on(event,'.star-item',function () {
            $(this).addClass('hover').prevAll().addClass('hover');
            $(this).nextAll().removeClass('hover');
        });
    }
   /* /!*分类跳转*!/
    $('#middle').on('click','.nav a',function () {
        var parentId = $(this).data('parentid') || '';
        var categoryId = $(this).data('categoryid') || '';
        var orderbyfield = $(this).data('orderbyfield');
        var newHref = '';
        var href = location.href;
        if(orderbyfield){
            newHref = href.split('?')[0]+'?page=1&orderByField='+orderbyfield;
            location.href = newHref;
            return;
        }
        if(!parentId && !categoryId){
            return;
        }
        newHref = href.split('?')[0]+'?page=1&parentId='+parentId+'&categoryId='+categoryId;
        location.href = newHref;
    });*/
    /*tab切换*/
    $(document).on('click','.tabs-nav span',function(){
        var $tabsCon = $('.tabs-con>div');
        var $this = $(this);
        var index = $this.index();
        $this.addClass('lmText').siblings().removeClass('lmText');
        $tabsCon.hide();
        $tabsCon.eq(index).show();
    });
   /* $('body').on('click',function () {
        $('#header').find('.header-user-nav-box').hide();
        $('#header').find('.car-summary-box').hide();
    });
    /!*头部个人中心导航展示*!/
    $('#header').on('click','.header-user',function () {
        event.stopPropagation();
        $('#header').find('.car-summary-box').hide();
        $(this).find('.header-user-nav-box').slideToggle();
    });*/
    /*分页点击页面跳转(后台分页*/
    function pageEvent() {
        $('body .paging').on('click','button',function () {
            var $page = $('body .paging');
            var type = $(this).data('page');
            var jumpPage = type;
            var currentPage = $page.data('current');
            var total = $page.data('total');
            var href = location.href;
            var newHref = '';
            if (type == 'jump'){
                var inputPage = $('body .paging').find('input').val();
                if(inputPage == currentPage
                    ||inputPage > total
                    ||inputPage < 1){
                    $('body .paging').find('input').val('');
                    return;
                }
                jumpPage = inputPage;
            }
            if (type == 'first'){
                jumpPage = 1;
            }
            if (type == 'prev'){
                jumpPage = currentPage - 1;
            }
            if (type == 'next'){
                jumpPage = currentPage + 1;
            }
            if (type == 'end'){
                jumpPage = total;
            }
            if(isNaN(jumpPage/1)){
                jumpPage = 1;
            }
            if(href.indexOf('page=') > -1){
                newHref = href.replace(/page=\d/, "page="+jumpPage);
            }else {
                newHref = href + '?page='+jumpPage;
            }
            location.href = newHref;
        });
        $('body .paging').on('keyup','input',function (e) {
            var $page = $('body .paging');
            var jumpPage = $(this).val();
            var currentPage = $page.data('current');
            var total = $page.data('total');
            var href = location.href;
            var newHref = '';
            if((e.keyCode==13)&&(jumpPage/1 >= 1) && (jumpPage/1 <= total/1) && jumpPage != currentPage){
                if(href.indexOf('page=') > -1){
                    newHref = href.replace(/page=\d/, "page="+jumpPage);
                }else {
                    newHref = href + '?page='+jumpPage;
                }
                location.href = newHref;
            }
        });
    }
    function scrollEvent(callback) {
        var flag = true;
        var pageH = Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
        var scrollH = document.documentElement.scrollTop || document.body.scrollTop;
        var offsetH = _getClientHeight();
        var rightH = $('#right').height();
        if(scrollH - rightH > 20){ /*右侧公告*/
            $('#right .need-fixed:eq(0)').addClass('fixed-notice');
        }
        if(scrollH < rightH){
            $('#right .need-fixed:eq(0)').removeClass('fixed-notice');
        }
        if( pageH-scrollH - offsetH < 100) { /*距离底部100高度数据加载*/
            if(BASE.COMMON.SCROLLFLAG && callback && typeof callback == 'function' && flag){
                BASE.COMMON.SCROLLFLAG =  false;
                callback();
            }
        }
    }
    //获取窗口可视范围的高度
    function _getClientHeight(){
        var clientHeight=0;
        if(document.body.clientHeight && document.documentElement.clientHeight){
            clientHeight = (document.body.clientHeight < document.documentElement.clientHeight)
                ? document.body.clientHeight
                : document.documentElement.clientHeight;
        }else{
           clientHeight = (document.body.clientHeight > document.documentElement.clientHeight)
               ? document.body.clientHeight
               : document.documentElement.clientHeight;
        }
        return clientHeight;
    }
    /*收提问藏*/
    function collectQes(obj) {
        var id = $(obj).data('id');
        BASE.apiPost('/device/mutualQuestion/collect',{ id: id },function () {
            $(obj).hide().next().fadeIn();
        })
    }
    /*取消提问收藏*/
    function uncollectQes(obj) {
        var id = $(obj).data('id');
        BASE.apiPost('/device/mutualQuestion/uncollect',{ id: id },function () {
            $(obj).hide().prev().fadeIn();
        })
    }
    /*收提源码*/
    function collectSource(obj) {
        var id = $(obj).data('id');
        BASE.apiPost('/device/sourceCode/collect',{ id: id },function () {
            $(obj).hide().next().fadeIn();
        })
    }
    /*取消源码收藏*/
    function uncollectSource(obj) {
        var id = $(obj).data('id');
        BASE.apiPost('/device/sourceCode/uncollect',{ id: id },function () {
            $(obj).hide().prev().fadeIn();
        })
    }
    /*收提博客*/
    function collectBlog(obj) {
        var id = $(obj).data('id');
        BASE.apiPost('/device/blog/collect',{ id: id },function () {
            $(obj).hide().next().fadeIn();
        })
    }
    /*取消源码收藏*/
    function uncollectBlog(obj) {
        var id = $(obj).data('id');
        BASE.apiPost('/device/blog/uncollect',{ id: id },function () {
            $(obj).hide().prev().fadeIn();
        })
    }
    /*所有分享送金币*/
    if(getUserId()){
        $('body').on('click','.share-item',function () {
            BASE.postHttp('/device/member/share');
        });
        $('body').on('mouseenter','.icon-wechat',function () {
            BASE.postHttp('/device/member/share');
        });
    }
    /*右侧滚动按钮特效*/
    function scrollTop(h,delay) {
        delay = delay || 400;
        h = h || 500;
        $('html').animate({scrollTop: h}, delay);$('body').animate({scrollTop: h}, delay);
    }
    return {
        getUserData:getUserData,
        getUserId:getUserId,
        getId: getId,
        getcommentResult: getcommentResult,
        userInfoFill:userInfoFill,
        replyPrev: replyPrev,
        getCommentReply: getCommentReply,
        addComment: addComment,
        addReply: addReply,
        getStatus: getStatus,
        getQQList:getQQList,
        /*关注*/
        isNotice:isNotice,
        noticeToMember:noticeToMember,
        cancelNotice:cancelNotice,
        buyVip:buyVip,
        getArea:getArea,
        getGoodsPrice:getGoodsPrice,
        collectVideo:collectVideo,
        cancelcollectVideo:cancelcollectVideo,
        getCommentScore:getCommentScore,
        addCommentScore:addCommentScore,
        addbbsClick:addbbsClick,
        recommendDarenList:recommendDarenList,
        collectQes:collectQes,
        uncollectQes:uncollectQes,
        collectSource:collectSource,
        uncollectSource:uncollectSource,
        collectBlog:collectBlog,
        uncollectBlog:uncollectBlog,
        commentStar: commentStar,
        urlLeftNav: urlLeftNav,
        ulrContentNav: ulrContentNav,
        scrollEvent:scrollEvent,
        SCROLLFLAG:SCROLLFLAG,
        pageEvent:pageEvent,
        getClientHeight:_getClientHeight,
        scrollTop:scrollTop,
    };
    /***********************公用事件绑定end***********************/
})();

